package kr.ac.kaist.simplefileexplorer;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ListView;

import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.Drive.Files;
import com.google.api.services.drive.Drive.Permissions;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.FileList;
import com.google.api.services.drive.model.Permission;
import com.google.api.services.drive.model.PermissionList;

public class GoogleDriveChangePermissionActivity extends Activity{

	 private static final int SEND_REQUEST_SUCCEED = 1;
	 private static final int SEND_REQUEST_FAILED = 2; 
	 private static final int REQUEST_AUTHORIZATION = 3;
	 
	 private static Uri fileUri;
	 private static Drive service;

	 private static String filename;
	 private GoogleAccountCredential credential;
	 
	 private static String shareURL;

	 
	 ProgressDialog dialog;
	 ProgressHandler handler;
	 
	 List<File> file_list;
	 private ListView listViewRest;
	 
	 Context ctx;	
	@Override
	 public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_general_list);
		  
		ctx = this;
		  
		file_list = new ArrayList<File>();
		  
		handler = new ProgressHandler(); 
		
		Intent intent = getIntent();
		String accountName = intent.getExtras().getString("AccountName");
		String fildId = intent.getExtras().getString("FileID");

		
		try { 
			changePermission(accountName, fildId);      		
		} catch (IOException e) {  
	   // TODO Auto-generated catch block      e.printStackTrace();
		}	
		showWaitingPopUp();
	 }
	
	 private Drive getDriveService(GoogleAccountCredential credential) {
		  return new Drive.Builder(AndroidHttp.newCompatibleTransport(),
		    new GsonFactory(), credential).build();
	 }
	 
	 protected void showWaitingPopUp(){
		 	dialog = new ProgressDialog(this);
				dialog.setTitle("Wait...");
				dialog.setMessage("Please wait while querying...");
				dialog.setIndeterminate(true);
				dialog.setCancelable(false);
				dialog.show();	
	 }
		 
	 protected void removeWaitingPopup(){
	 	dialog.dismiss();
	 }
	 
	 private void changePermission(String accountName, String fileId) throws IOException {
	     final String fild_Id = fileId;

		 credential = GoogleAccountCredential.usingOAuth2(this,Arrays.asList(DriveScopes.DRIVE_FILE));		
		 credential.setSelectedAccountName(accountName);
		 final Drive final_service = getDriveService(credential); 	     
	     Thread t = new Thread(new Runnable() {
	   @Override
	   public void run() {   
		   Permission newPermission = new Permission();
		   File file = new File(); 
		   
		    newPermission.setValue("");
		    newPermission.setType("anyone");
		    newPermission.setRole("reader");
		    try {
		    	final_service.permissions().insert(fild_Id, newPermission).execute();
		    } catch (IOException e) {
		      System.out.println("An error occurred: " + e);
		    }
		    
		    //share done. read URL
		    try {
		        file = final_service.files().get(fild_Id).execute();

		        System.out.println("Title: " + file.getTitle());
		        System.out.println("Description: " + file.getDescription());
		        System.out.println("shareURL: " + file.getWebContentLink());

		      } catch (IOException e) {
		        System.out.println("An error occured: " + e);
		      }
	        
		    shareURL = file.getWebContentLink();  	   
	 	   Message msg = handler.obtainMessage();     
	 	   
			msg.what = SEND_REQUEST_SUCCEED;
			String hi = new String("Query Done");
			msg.obj = hi;
			
			handler.sendMessage(msg); 	   
	   }
	  });
	  t.start();

	   }	 
	 

	 public class ProgressHandler extends Handler{
		 	public void handleMessage(Message msg){
		 		
		 		super.handleMessage(msg);
		 		
		 		switch(msg.what)
		 		{
		 			case SEND_REQUEST_SUCCEED:
		 				//request done. update ui
		 				removeWaitingPopup();
		 	              Intent intent = new Intent();
		 	              intent.putExtra("ShareURL", shareURL);

		 	              setResult(RESULT_OK, intent);
		 	              finish();
		 			break;
		 			case SEND_REQUEST_FAILED:
		 				//request failed. update ui
		 				removeWaitingPopup(); 	   	

		 			break;   			
		 			default:
		 			break;
		 		}
		 		
		 	}
		 } 
		}


